<!DOCTYPE html>
<!--
Copyright 2016 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/utils.html">
<link rel="import" href="/tracing/ui/analysis/generic_object_view.html">
<link rel="import" href="/tracing/value/ui/diagnostic_span_behavior.html">

<dom-module id="tr-v-ui-generic-set-span">
  <template>
    <tr-ui-a-generic-object-view id="generic"></tr-ui-a-generic-object-view>

    <div id="links"></div>
  </template>
</dom-module>

<script>
'use strict';
tr.exportTo('tr.v.ui', function() {
  function isLinkTuple(value) {
    return ((value instanceof Array) &&
            (value.length === 2) &&
            (typeof value[0] === 'string') &&
            tr.b.isUrl(value[1]));
  }

  Polymer({
    is: 'tr-v-ui-generic-set-span',
    behaviors: [tr.v.ui.DIAGNOSTIC_SPAN_BEHAVIOR],

    updateContents_() {
      this.$.generic.style.display = 'none';
      this.$.links.textContent = '';
      if (this.diagnostic === undefined) return;
      const values = Array.from(this.diagnostic);

      let areAllStrings = true;
      let areAllNumbers = true;
      for (const value of values) {
        if (typeof value !== 'number') {
          areAllNumbers = false;
          if (typeof value !== 'string' && !isLinkTuple(value)) {
            areAllStrings = false;
            break;
          }
        }
      }

      if (!areAllStrings) {
        this.$.generic.style.display = '';
        this.$.generic.object = values;
        return;
      }

      if (areAllNumbers) {
        values.sort((x, y) => x - y);
      } else {
        values.sort();
      }

      for (const value of values) {
        const link = {
          textContent: '' + value,
          display: 'block'
        };
        if (isLinkTuple(value)) {
          link.textContent = value[0];
          link.href = value[1];
        } else if (tr.b.isUrl(value)) {
          link.href = value;
        }
        if (this.name_ === tr.v.d.RESERVED_NAMES.TRACE_URLS) {
          link.textContent = value.substr(1 + value.lastIndexOf('/'));
        }
        const linkEl = tr.ui.b.createLink(link);
        if (link.href) {
          linkEl.target = '_blank';
          // In case there's a listener in the hierarchy that calls
          // preventDefault(), stop the event from propagating to it so that
          // clicking the link always opens it in a new tab.
          linkEl.addEventListener('click', e => e.stopPropagation());
        }
        this.$.links.appendChild(linkEl);
      }
    }
  });

  return {
  };
});
</script>
